package v1

import (
	"DuckShop/internal/user/proto/users"
	"context"
	"google.golang.org/protobuf/types/known/timestamppb"
	"strconv"
)

type UserAPI interface {
	ValidatorEnterUser(params *UserEnterParams) (bool, int64, error)
	CreateUser(user *CreateUserParams) error
	GetUserByID(id string) (*users.User, error)
	UpdateUser(user *UpdateUserParams) (*users.User, error)
	DeleteUser(id string) error
	GetUserList(params *GetUserListParams) (*users.ListUsersResponse, error)
}

type UserAPIImpl struct {
	client users.DuckUserServiceClient // 用户服务客户端实例～
}

func (u UserAPIImpl) UpdateUser(user *UpdateUserParams) (*users.User, error) {
	updateUser, err := u.client.UpdateUser(context.Background(), &users.UpdateUserRequest{User: &users.User{
		Nickname: user.Nickname,
		Birthday: timestamppb.New(user.Birthday),
		Gender:   user.Gender,
	}})
	if err != nil {
		return nil, err
	}
	return updateUser.User, nil
}

func (u UserAPIImpl) DeleteUser(id string) error {
	parseUint, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		return err
	}
	_, err = u.client.DeleteUser(context.Background(), &users.DeleteUserRequest{
		UserId: parseUint,
	})
	if err != nil {
		return err
	}
	return nil
}

func (u UserAPIImpl) ValidatorEnterUser(params *UserEnterParams) (bool, int64, error) {
	password, err := u.client.ValidatePassword(context.Background(), &users.ValidatePasswordRequest{
		Username: params.Username,
		Password: params.Password,
	})
	if err != nil {
		return false, 0, err
	}
	return password.IsValid, int64(password.GetUserId()), err
}

func (u UserAPIImpl) GetUserByID(id string) (*users.User, error) {
	i, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		return nil, err
	}
	user, err := u.client.GetUser(context.Background(), &users.GetUserRequest{UserId: i})
	if err != nil {
		return nil, err
	}
	return user.User, nil
}

func (u UserAPIImpl) GetUserList(params *GetUserListParams) (*users.ListUsersResponse, error) {
	listUsers, err := u.client.ListUsers(context.Background(), &users.ListUsersRequest{
		PageSize:   uint32(params.PageSize),
		PageNumber: uint32(params.PageNumber),
	})
	return listUsers, err
}

// CreateUser client 调用 rpc CreateUser
func (u UserAPIImpl) CreateUser(params *CreateUserParams) error {
	_, err := u.client.CreateUser(context.Background(), &users.CreateUserRequest{User: &users.User{
		Mobile:   params.Mobile,
		Password: params.Password,
		Nickname: params.Nickname,
		Birthday: timestamppb.New(params.Birthday),
		Gender:   params.Gender,
		Role:     params.Role,
		Username: params.Username,
	}})
	return err
}
